<?php
// $Id$

/**
 * Controller_Users 控制器
 */
class Controller_Users extends Controller_Abstract
{

	function actionIndex()
	{
        // 为 $this->_view 指定的值将会传递数据到视图中
		# $this->_view['text'] = 'Hello!';
	}
	function actionRegister()
	{
		$form = new Form_UserLogin(url('users/register'));
		
		if ($this->_context->isPost() && $form->validate($_POST))
		{
			try
			{
				$user = new User($form->values());
				$user->save();
				
				return $this->_redirect(url('default/index'));
			}
			catch (AclUser_DuplicateUsernameException $ex)
			{
				$form['username']->invalidate("您要注册用户名 {$user->username} 已经存在了");
			}
		}
		
		$this->_view['form'] = $form;
	}
	function actionLogin()
	{
		$form = new Form_UserLogin(url('users/login'));
		$form->_subject = '登录';
		
		if ($this->_context->isPost() && $form->validate($_POST))
		{
			try
			{
				$user = User::meta()->validateLogin($form['username']->value, $form['password']->value);
				$this->_app->changeCurrentUser($user->aclData(), 'MEMBER');
				
				return $this->_redirect(url('default/index'));
			}
			catch(AclUser_UsernameNotFoundException $ex)
			{
				$form['username']->invalidate("您输入的用户名 {$form['username']->value} 不存在");
			}
			catch(AclUser_WrongPasswordException $ex)
			{
				$form['password']->invalidate("您输入的密码不正确");
			}
		}
		$this->_view['form'] = $form;
		$this->_viewname = 'register';
	}
	function actionLogout()
	{
		$this->_app->cleanCurrentUser();
		return $this->_redirect(url('default/index'));
	}
	function actionChangePasswd()
	{
		$form = new Form_ChangePasswd(url('users/changepasswd'));
		
		if ($this->_context->isPOST() && $form->validate($_POST))
		{
			try
			{
				$current_user = $this->_app->currentUser();
				
				User::meta()->changePassword(
					$current_user['username'],
					$form['new_password']->value,
					$form['old_password']->value
				);
				return $this->_redirectMessage(
					'修改密码成功',
					'您的登录密码已经修改成功，下次请使用新密码。',
					url('default/index')
				);
			}
			catch (AclUser_WrongPasswordException $ex)
			{
				$form['old_password']->invalidate('您输入的现用密码不正确');
			}
		}
		
		$this->_view['form'] = $form;
		$this->_viewname = 'register';
	}
}


